package aes.client;

import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.util.*;

import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;

import common.*;
import javax.swing.table.*;

public class QuestionsManagerUI extends JPanel implements ActionListener, ListSelectionListener, Observer {

	/**
	 * 
	 */
	private static final long serialVersionUID = -8421199899722861801L;

	private ClientUI ui;
	private Client c;

	private JTable list;
	private JButton btnBack;
	private JButton btnAdd;
	private JButton btnUpdate;
	private JButton btnDelete;

	/**
	 * Constructor
	 * @param ui reference of parent frame
	 */ 
	@SuppressWarnings("serial")
	public QuestionsManagerUI(Client c, ClientUI ui) {
		this.c = c;
		this.ui = ui;
		JFrame frame = new JFrame();
		frame.setSize(640, 480);
		frame.add(this);
		
		// Handle messages from server.
		c.addObserver(this);

		setLayout(new GridBagLayout());

		JPanel panel = new JPanel();
		panel.setBorder(new LineBorder(new Color(0, 0, 0), 2, true));
		panel.setPreferredSize(new Dimension(600,400));

		GridBagConstraints gbc_panel = new GridBagConstraints();
		gbc_panel.insets = new Insets(5, 0, 5, 0);
		gbc_panel.gridx = 0;
		gbc_panel.gridy = 0;
		add(panel,gbc_panel);
		GridBagLayout gbl_panel = new GridBagLayout();
		gbl_panel.rowWeights = new double[]{0.0, 1.0};
		gbl_panel.columnWeights = new double[]{0.0, 1.0};
		panel.setLayout(gbl_panel);

		JLabel lblAesTitle = new JLabel("Questions Manager:");
		lblAesTitle.setHorizontalAlignment(SwingConstants.CENTER);
		lblAesTitle.setBounds(7, 10, 70, 17);
		lblAesTitle.setFont(new Font("Tahoma", Font.BOLD, 14));

		GridBagConstraints gbc_lblAesTitle = new GridBagConstraints();
		gbc_lblAesTitle.gridwidth = 4;
		gbc_lblAesTitle.fill = GridBagConstraints.BOTH;
		gbc_lblAesTitle.insets = new Insets(5, 0, 5, 5);
		gbc_lblAesTitle.gridx = 0;
		gbc_lblAesTitle.gridy = 0;
		panel.add(lblAesTitle, gbc_lblAesTitle);

		list = new JTable(){
			public boolean isCellEditable(int rowIndex, int colIndex) {
				return false; //Disallow the editing of any cell
			}};
			list.setModel(new DefaultTableModel(
					new Object[][] {
					},
					new String[] {
							"Question #", "Subject", "Question" , "ID"
					}
					) {
				/**
				 * 
				 */
				private static final long serialVersionUID = -4567261985989300298L;
				@SuppressWarnings("rawtypes")
				Class[] columnTypes = new Class[] {
					String.class, String.class, String.class , String.class
				};
				@SuppressWarnings({ "unchecked", "rawtypes" })
				public Class getColumnClass(int columnIndex) {
					return columnTypes[columnIndex];
				}
			});
			list.removeColumn(list.getColumnModel().getColumn(3));
			list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
			list.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
			list.getColumnModel().getColumn(0).setPreferredWidth(70);
			list.getColumnModel().getColumn(1).setPreferredWidth(80);
			list.getColumnModel().getColumn(2).setPreferredWidth(433);
			list.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
			JScrollPane scrollPane = new JScrollPane(list);
			list.setFillsViewportHeight(true);
			list.getSelectionModel().addListSelectionListener(this);
			GridBagConstraints gbc_list = new GridBagConstraints();
			gbc_list.insets = new Insets(5, 5, 5, 5);
			gbc_list.fill = GridBagConstraints.BOTH;
			gbc_list.gridwidth = 4;
			gbc_list.gridx = 0;
			gbc_list.gridy = 1;
			panel.add(scrollPane, gbc_list);

			btnBack = new JButton("Back", new ImageIcon(QuestionsManagerUI.class.getResource("/aes/client/images/back.png")));
			btnBack.addActionListener(this); 
			GridBagConstraints gbc_btnBack = new GridBagConstraints();
			gbc_btnBack.insets = new Insets(5, 5, 5, 5);
			gbc_btnBack.gridx = 0;
			gbc_btnBack.gridy = 3;
			panel.add(btnBack, gbc_btnBack);
			btnBack.setBounds(353, 7, 57, 23);

			btnAdd = new JButton("New", new ImageIcon(QuestionsManagerUI.class.getResource("/aes/client/images/Plus.png")));
			btnAdd.addActionListener(this); 
			GridBagConstraints gbc_btnAdd = new GridBagConstraints();
			gbc_btnAdd.insets = new Insets(5, 5, 5, 5);
			gbc_btnAdd.gridx = 1;
			gbc_btnAdd.gridy = 3;
			panel.add(btnAdd, gbc_btnAdd);
			btnAdd.setBounds(353, 7, 57, 23);

			btnUpdate = new JButton("Edit", new ImageIcon(QuestionsManagerUI.class.getResource("/aes/client/images/edit.png")));
			btnUpdate.addActionListener(this); 
			GridBagConstraints gbc_btnUpdate = new GridBagConstraints();
			gbc_btnUpdate.gridwidth = 1;
			gbc_btnUpdate.insets = new Insets(5, 5, 5, 5);
			gbc_btnUpdate.gridx = 2;
			gbc_btnUpdate.gridy = 3;
			panel.add(btnUpdate, gbc_btnUpdate);
			btnUpdate.setBounds(353, 7, 57, 23);

			btnDelete = new JButton("Delete", new ImageIcon(QuestionsManagerUI.class.getResource("/aes/client/images/Cancel.png")));
			btnDelete.addActionListener(this); 
			GridBagConstraints gbc_btnDelete = new GridBagConstraints();
			gbc_btnDelete.insets = new Insets(5, 5, 5, 5);
			gbc_btnDelete.gridx = 3;
			gbc_btnDelete.gridy = 3;
			panel.add(btnDelete, gbc_btnDelete);
			btnDelete.setBounds(353, 7, 57, 23);
			
			if (ui.getUser() instanceof Principal) {
				btnAdd.setVisible(false);
				btnDelete.setVisible(false);
				btnUpdate.setIcon(new ImageIcon(QuestionsManagerUI.class.getResource("/aes/client/images/view.png")));
				btnUpdate.setText("View");
			}
	}

	/**
	 * Buttons click event handler
	 */
	@SuppressWarnings("static-access")
	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource().equals(btnBack)) {
			// Back.
			ui.SetContent(ui.MAIN_SCREEN);
		}
		else if (e.getSource().equals(btnAdd)) {
			// Add new question.
			ui.SetContent(ui.QUESTION_EDITOR_SCREEN);
		}
		else if (e.getSource().equals(btnUpdate)) {
			// Update question.
			ui.SetContent(ui.QUESTION_EDITOR_SCREEN);
			DefaultTableModel model =(DefaultTableModel) list.getModel();
			Vector<?> o1 = (Vector<?>) model.getDataVector().get(list.getSelectedRow());
			int id = Integer.parseInt((String)o1.get(3));
			QuestionEditorUI panel= ((QuestionEditorUI)ui.getContentPane());
			panel.setQuestionID(id);

		}
		else if (e.getSource().equals(btnDelete)) {
			// Delete question.
			if (JOptionPane.showConfirmDialog(ui , "Are you sure you want to delete question ?", "Confirm", JOptionPane.OK_CANCEL_OPTION) == 0) {
				// Delete.
				DefaultTableModel model =(DefaultTableModel) list.getModel();
				Vector<?> o1 = (Vector<?>) model.getDataVector().get(list.getSelectedRow());
				int id = Integer.parseInt((String)o1.get(3));
				CommandMessage msg = new CommandMessage(CommandMessage.DELETE_QUESTION, new Object[] {id});
				try {
					c.sendToServer(msg);
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
	}

	/**
	 * Updates questions list
	 * 
	 * @see this function is thread safed, so use it in order to update interface from the other thread
	 */
	public void UpdateUI() {
		javax.swing.SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				getQuestionsList();  
			}
		});
	}

	/**
	 * Load Questions list from the server
	 */
	@SuppressWarnings("static-access")
	private void getQuestionsList() {
		//create a message for server to retrieve the data params (ORDER, USER TYPE , ID)
		CommandMessage msg = new CommandMessage(CommandMessage.GET_QUESTIONS, new String[] {(ui.getUser() instanceof Principal)? "PRINCIPAL":"TEACHER", Integer.toString(ui.getUser().getId())});
		try {
			c.sendToServer(msg);
		} catch (IOException e) {
			e.printStackTrace();
			ui.ShowMessageBox("Error", "Can't retrieve questions list", JOptionPane.ERROR_MESSAGE);
		}
	}

	/**
	 * Server message received event handler
	 */
	@Override
	public void update(Observable arg0, Object arg1) {
		//checks if object is CommandMessage
		if (arg1 instanceof CommandMessage) {
			CommandMessage ms=(CommandMessage)arg1; //casting
			//checks if command is ACKNOWLEDGE_MESSAGE and parameters are GET_QUESTIONS
			if (ms.getCommand().equals(CommandMessage.ACKNOWLEDGE_MESSAGE) && ((String)ms.getParams()[0]).equals(CommandMessage.GET_QUESTIONS)) {
				//gets Questions array from server answer (query answer from __ )
				Question[] questions = (Question[]) ms.getParams()[2];
				//disables buttons
				btnUpdate.setEnabled(false); 
				btnDelete.setEnabled(false);
				if (questions != null) {
					// Bind data. to table
					DefaultTableModel model =(DefaultTableModel) list.getModel();
					model.setRowCount(0);
					for (Question q:questions) {
						String[] row = new String[4];
						row[0] = String.format("%03d", q.getQuestionID());
						row[1] = q.getSubjectName();
						row[2] = q.getQuestion();
						row[3] = Integer.toString(q.getId());
						model.addRow(row);
					}
					list.setModel(model);
				}
			}
			//if question deleted
			if (ms.getCommand().equals(CommandMessage.ACKNOWLEDGE_MESSAGE) && ((String)ms.getParams()[0]).equals(CommandMessage.DELETE_QUESTION)) {
				// Update questions list.
				getQuestionsList();
			}
		}
	}

	/**
	 * Questions list selected item changed event handler
	 */
	@Override
	public void valueChanged(ListSelectionEvent e) {
		// Row selection changed
		//int first = e.getFirstIndex();
		//int last = e.getLastIndex();

		btnUpdate.setEnabled(true);
		btnDelete.setEnabled(true);

	}

}
